from rest_framework import serializers
from .models import Banner,Notice,Collection,Area
from libs.baidu_ai import BaDuFace

class BannerSerializer(serializers.ModelSerializer):
    class Meta:
        model=Banner
        fields='__all__'
class NoticeSerializer(serializers.ModelSerializer):
    class Meta:
        model=Notice
        fields='__all__'

class CollectionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Collection
        fields = ['id', 'name', 'avatar', 'area']
        depth = 1  # area 外键关联详情拿到

class AreaSerializer(serializers.ModelSerializer):
    class Meta:
        model = Area
        fields = ['id', 'name', 'desc']

class CollectionSaveSerializer(serializers.ModelSerializer):  # 信泽序列化类
    class Meta:
        model = Collection
        fields = ['name', 'avatar', 'area']

    def create(self, validated_data):
        # 完成保存
        ai = BaDuFace()
        file_obj = validated_data.get('avatar')
        name = validated_data.get('name')
        name_pinyin = ai.name_to_pinyin(name)
        res = ai.add_user(file_obj, name_pinyin)
        if res.get('error_code') == 0:
            validated_data['face_token'] = res.get('result').get('face_token')
            validated_data['name_pinyin'] = name_pinyin
            instance = super().create(validated_data)
            return instance
        else:
            raise serializers.ValidationError({"msg": "人脸识别失败"})
    

class CollectionSaveSerializer(serializers.ModelSerializer):
    class Meta:
        model = Collection
        fields = ['name', 'avatar', 'area']

    def create(self, validated_data):
        instance = super().create(validated_data)
        return instance